/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { Module } from '@ohos/hvigor';

import { CommonConst } from '../../const/common-const.js';
import { ProjectModelImpl } from '../../model/project/project-model-impl.js';
import { ApiType } from '../../project/data/hap-extra-info.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { AppPlugin } from '../app-plugin.js';
import { AbstractModulePlugin } from '../common/abstract-module-plugin.js';
import { OhosPluginId } from '../common/ohos-plugin-id.js';
import { HapPlugin } from '../hap-plugin.js';
import { HarPlugin } from '../har-plugin.js';
import { HspPlugin } from '../hsp-plugin.js';

import { CorePluginBuilder } from './core-plugin-builder.js';

export class PluginBuilder extends CorePluginBuilder {
  private _log: OhosLogger = OhosLogger.getLogger(PluginBuilder.name);

  constructor(module: Module) {
    super(module);
  }

  createStageHapPlugin(): HapPlugin {
    return this.initPluginParam(new HapPlugin(this.module), true) as HapPlugin;
  }

  createStageHspPlugin(): HspPlugin {
    return this.initPluginParam(new HspPlugin(this.module), true) as HspPlugin;
  }

  createStageHarPlugin(): HarPlugin {
    return this.initPluginParam(new HarPlugin(this.module), false) as HarPlugin;
  }

  initPluginParam(plugin: AbstractModulePlugin, isHapModule: boolean): AbstractModulePlugin {
    const projectModel = this.createProjectModel();
    const moduleModel = this.createModuleModel(projectModel, isHapModule);

    return plugin
      .withProjectModel(projectModel)
      .withModuleModel(moduleModel)
      .withPluginApiType(ApiType.STAGE)
      .withRuntimeConfigFileName(CommonConst.MODULE_JSON5);
  }

  setUpModulePlugin(plugin: AbstractModulePlugin) {
    plugin.doModuleInspection();
    plugin.initModuleTaskService(false);
    plugin.initBuildOptionMap(this.module.getBuildProfilePath());
    plugin.initTargetDepends();
    plugin.initModuleCommonTasksForDiffApiType(false);
  }

  public createProjectModel(): ProjectModelImpl {
    const project = this.module.getProject();
    const appPlugin = project.getPluginById(OhosPluginId.OHOS_APP_PLUGIN) as AppPlugin;
    if (!appPlugin) {
      this._log.printErrorExit(
        'STAGE_NO_SYSTEM_PLUGIN',
        [`${[project.getBuildFilePath()]}.ts`],
        [[`${[project.getBuildFilePath()]}.ts`]]
      );
    }
    return appPlugin.getProjectModel() as ProjectModelImpl;
  }
}
